package dnl.dtools.grm.ssh;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import ch.ethz.ssh2.StreamGobbler;

/**
 * Encapsulates the result of a single ssh command.
 * 
 * @author daniel
 * 
 */
public class OngoingSshCommandResult {
	private InputStream stdout;

	private InputStream stderr;

	private OutputListener sysoutListener;
	private OutputListener syserrListener;
	private Thread t1;
	private Thread t2;
	private boolean stop;
	
	public OngoingSshCommandResult(InputStream stdout, InputStream stderr) {
		super();
		this.stdout = stdout;
		this.stderr = stderr;
	}
	
	public void setSyserrListener(OutputListener syserrListener) {
		this.syserrListener = syserrListener;
	}

	public void setSysoutListener(OutputListener sysoutListener) {
		this.sysoutListener = sysoutListener;
	}

	public void startStreamsExtraction(){
		stop = false;
		Runnable r1 = new Runnable(){
			public void run() {
				try {
					if(sysoutListener != null) {
						extractStream(stdout, sysoutListener);
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		Runnable r2 = new Runnable(){
			public void run() {
				try {
					if(syserrListener != null) {
						extractStream(stderr, syserrListener);
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		};
		t1 = new Thread(r1);
		t2 = new Thread(r2);
		t1.start();
		t2.start();
	}
	
	public void stop(){
		stop = true;
	}
	
	public void join(){
		try {
			t1.join();
			t2.join();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void extractStream(InputStream in, OutputListener listener) throws IOException {
		InputStream stdout = new StreamGobbler(in);
		BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
		while (true) {
			if(stop){
				return;
			}
			String line = br.readLine();
			if (line == null)
				break;
			listener.newOutputLine(line);
		}
	}
}
